package io.netty.example.splicing.delimiter;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import org.slf4j.LoggerFactory;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 类说明：使用自定义分隔符解决 粘包/半包问题 自己的业务处理
 */
@ChannelHandler.Sharable
public class DelimiterServerHandler extends ChannelInboundHandlerAdapter {
  
  private static final org.slf4j.Logger log = LoggerFactory.getLogger(DelimiterServerHandler.class);
  private AtomicInteger counter = new AtomicInteger(0);
  private AtomicInteger completeCounter = new AtomicInteger(0);
  
  /*** 服务端读取到网络数据后的处理*/
  @Override
  public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf in = (ByteBuf) msg;
    String request = in.toString(CharsetUtil.UTF_8);
    System.out.println("Server Accept[" + request
        + "] and the counter is:" + counter.incrementAndGet());
    log.info(Thread.currentThread().getName());
    String resp = "Hello," + request + ". Welcome to Netty World!"
        + DelimiterEchoServer.DELIMITER_SYMBOL;
    // 从 这里 回写消息
    ctx.writeAndFlush(Unpooled.copiedBuffer(resp.getBytes()));
  }
  
  /*** 服务端读取完成网络数据后的处理*/
  @Override
  public void channelReadComplete(ChannelHandlerContext ctx)
      throws Exception {
    ctx.fireChannelReadComplete();
    System.out.println("the ReadComplete count is "
        + completeCounter.incrementAndGet());
  }
  
  /*** 发生异常后的处理*/
  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    cause.printStackTrace();
    ctx.close();
  }
}
